package java_thinking.unit_18_IO.exercise;

import java.io.*;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2020/3/30 8:43
 */

public class CloneUtil1<T> {

    public static <T> T cloneTo(T t) {
        ByteArrayOutputStream byteOutStream = new  ByteArrayOutputStream();
        ObjectOutputStream objOutputStream = null;
        ObjectInputStream objInputStream = null;
        T r = null;
        try {
            objOutputStream = new ObjectOutputStream(byteOutStream);
            objOutputStream.writeObject(t);
            objOutputStream.close();
            objInputStream = new ObjectInputStream(new ByteArrayInputStream(byteOutStream.toByteArray()));
            r = (T) objInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(objOutputStream!=null){
                try {
                    objOutputStream.close();
                    objOutputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objInputStream!=null){
                try {
                    objInputStream.close();
                    objInputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return r;
    }
}
